import type { ProjectConfig, TodoItem } from '@/lib/types'
import { create } from 'zustand'
import { persist } from 'zustand/middleware'

export interface OpenaiConfig {
    apiKey: string
    baseURL: string
}

interface AppState {
    // 提示词和生成内容
    prompt: string
    concurrentLimit: number
    apiKey: string
    baseURL: string
    todoList: TodoItem[]
    selectedModel: string
    projectStructure: string

    // 项目配置
    projectConfig: ProjectConfig

    // UI状态
    isLoading: boolean
    activeTab: string
    error: string | null

    // 操作方法
    setPrompt: (prompt: string) => void
    setTodoList: (todoList: TodoItem[]) => void
    addTodoItem: (todoItem: TodoItem) => void
    updateTodoItem: (id: number, updates: Partial<TodoItem>) => void
    removeTodoItem: (id: number) => void
    toggleTodoSelection: (id: number) => void
    selectAllTodos: () => void
    deselectAllTodos: () => void
    setSelectedModel: (modelId: string) => void
    setProjectStructure: (structure: string) => void

    setProjectConfig: (config: Partial<ProjectConfig>) => void

    setIsLoading: (isLoading: boolean) => void
    setConcurrentLimit: (limit: number) => void
    setActiveTab: (tab: string) => void
    setError: (error: string | null) => void

    getSelectedTodos: () => TodoItem[]
}

export const useAppStore = create<AppState>()(
    persist(
        (set, get) => ({
            // 初始状态
            prompt: '',
            concurrentLimit: 20,
            apiKey: process.env.NEXT_PUBLIC_API_KEY as string,
            baseURL: process.env.NEXT_PUBLIC_BASE_URL as string,
            todoList: [],
            selectedModel: 'qwen-plus',
            projectStructure: '',

            projectConfig: {
                name: 'vue-project',
                description: '使用Vue3、TypeScript、Vite和TailwindCSS创建的项目',
                vueVersion: '3.3',
                includeRouter: true,
                includePinia: true,
                includeVitest: false,
                includeEslint: true,
            },

            isLoading: false,
            activeTab: 'generator',
            error: null,

            // 操作方法
            setPrompt: (prompt) => set({ prompt }),

            setTodoList: (todoList) => set({ todoList }),

            addTodoItem: (todoItem) =>
                set((state) => ({
                    todoList: [...state.todoList, todoItem],
                })),

            updateTodoItem: (id, updates) =>
                set((state) => ({
                    todoList: state.todoList.map((item) => (item.id === id ? { ...item, ...updates } : item)),
                })),

            removeTodoItem: (id) =>
                set((state) => ({
                    todoList: state.todoList.filter((item) => item.id !== id),
                })),

            toggleTodoSelection: (id) =>
                set((state) => ({
                    todoList: state.todoList.map((item) => (item.id === id ? {
                        ...item,
                        selected: !item.selected
                    } : item)),
                })),

            selectAllTodos: () =>
                set((state) => ({
                    todoList: state.todoList.map((item) => ({ ...item, selected: true })),
                })),

            deselectAllTodos: () =>
                set((state) => ({
                    todoList: state.todoList.map((item) => ({ ...item, selected: false })),
                })),

            setSelectedModel: (modelId) => set({ selectedModel: modelId }),

            setProjectStructure: (structure) => set({ projectStructure: structure }),

            setProjectConfig: (config) =>
                set((state) => ({
                    projectConfig: { ...state.projectConfig, ...config },
                })),

            setIsLoading: (isLoading) => set({ isLoading }),
            setConcurrentLimit: (limit) => set({ concurrentLimit: limit }),
            setApiKey: (apiKey: string) => set({ apiKey }),
            setBaseURL: (baseURL: string) => set({ baseURL }),

            setActiveTab: (tab) => set({ activeTab: tab }),

            setError: (error) => set({ error }),

            getSelectedTodos: () => {
                return get().todoList.filter((item) => item.selected)
            },
        }),
        {
            name: 'vue-generator-storage',
            partialize: (state) => ({
                projectConfig: state.projectConfig,
                selectedModel: state.selectedModel,
            }),
        }
    )
)

export const useOpenaiConfig = (): OpenaiConfig => {
    const { baseURL, apiKey } = useAppStore();
    return {
        baseURL,
        apiKey,
    };
}
